
#include <algorithm>
#include <iostream>

struct ListNode {
  int val;
  ListNode* next;

  ListNode() : val(0), next(nullptr) {}
  explicit ListNode(int val) : val(val), next(nullptr) {}
  ListNode(int val, ListNode* next) : val(val), next(next) {}
};

class Solution {
 public:
  ListNode* removeNthFromEnd(ListNode* head, int n) {
    int sz = 0;
    for (ListNode* p = head; p != nullptr; p = p->next, sz++)
      ;

    int index = sz - n;
    if (index == 0) {
      head = head->next;
    } else {
      ListNode* p = head;
      for (int i = 0; i < index - 1; ++i) {
        p = p->next;
      }
      p->next = p->next->next;
    }
    return head;
  }
};
